package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper,Brand> implements BrandService {


    private final CategoryBrandService categoryBrandService;


    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        // 1.分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        // 2.分页
        Page<Brand> info = new Page<>(page, rows);
        // 3.判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(info);
        // 5.封装结果
        List<Brand> list = info.getRecords();
        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(list));
    }
    @Override
    public List<BrandDTO> queryBrandByCategory(Long id){
        List<Brand> list = getBaseMapper().queryByCategoryId(id);
        return BrandDTO.convertEntityList(list);
    }

    public BrandServiceImpl(CategoryBrandService categoryBrandService){
        this.categoryBrandService = categoryBrandService;
    }
    @Transactional
    @Override
    public void saveBrand(BrandDTO brandDTO){
        Brand brand = brandDTO.toEntity(Brand.class);
// 保存brand
        save(brand);
         /* // 2.获取分类id， 包含手机、空调、洗衣机
        List<Long> categoryIds = brandDTO.getCategoryIds();
        // 3.封装中间表对象集合
        Long brandId = brand.getId();// 小米

        List<CategoryBrand> categoryBrands = new ArrayList<>();
        for (Long categoryId : categoryIds) {
            // 创建中间表对象
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            categoryBrands.add(categoryBrand);
        }*/
        // 封装中间表对象的集合
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream().map(id -> CategoryBrand.of(id, brand.getId())).collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(list);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        // 1.更新品牌
        boolean success = updateById(brandDTO.toEntity(Brand.class));
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500, "更新品牌失败！");
        }
        // 2.根据品牌id删除中间表数据
        success = categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500,"更新品牌失败，删除中间表数据出错");
        }
        // 3.重新插入中间表数据
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brandDTO.getId()))
                .collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(list);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        //TODO 什么样的品牌才能被删除，不满足条件的一定不能删除（有人用）

        removeById(id);

        //根据id删除中间表信息
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",id));
    }
}
